﻿using System;
using System.Collections.Generic;

using System.Text;
using System.IO;
using System.Reflection;

namespace RoughJs.Ast
{
    /// <summary>
    /// 2010-01-5 ----- 2010-01-29
    /// 陈曦 1.0
    /// Microsoft Public License (Ms-PL)
    ///This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
    ///1. Definitions
    ///The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
    ///A "contribution" is the original software, or any additions or changes to the software.
    ///A "contributor" is any person that distributes its contribution under this license.
    ///"Licensed patents" are a contributor's patent claims that read directly on its contribution.
    ///2. Grant of Rights
    ///(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
    ///(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
    ///3. Conditions and Limitations
    ///(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
    ///(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
    ///(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
    ///(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
    ///(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 
    /// </summary>
    public class Kit
    {
        public static Exception codeBug() { return new Exception(); }
        /**
 * If character <tt>c</tt> is a hexadecimal digit, return
 * <tt>accumulator</tt> * 16 plus corresponding
 * number. Otherise return -1.
 */
        public static int xDigitToInt(int c, int accumulator)
        {

            // Use 0..9 < A..Z < a..z
            if (c <= '9')
            {
                c -= '0';
                if (0 <= c) { goto check; }
            }
            else if (c <= 'F')
            {
                if ('A' <= c)
                {
                    c -= ('A' - 10);
                    goto check;
                }
            }
            else if (c <= 'f')
            {
                if ('a' <= c)
                {
                    c -= ('a' - 10);
                    goto check;
                }
            }
            return -1;

        check: ;
            return (accumulator << 4) | c;
        }

        public static Type classOrNull(String className)
        {
            try
            {
                return Type.GetType(className);
            }
            catch
            {
                //  throw ex;
            }
            return null;
        }

        public static String readReader(Stream r)
        {
            char[] buffer = new char[512];
            StreamReader reader = new StreamReader(r);
            int cursor = 0;
            for (; ; )
            {
                int n = reader.Read(buffer, cursor, buffer.Length - cursor);
                if (n < 0) { break; }
                cursor += n;
                if (cursor == buffer.Length)
                {
                    char[] tmp = new char[buffer.Length * 2];
                    Array.Copy(buffer, 0, tmp, 0, cursor);
                    buffer = tmp;
                }
            }
            return new String(buffer, 0, cursor);
        }
        public static Object newInstanceOrNull(Type cl)
        {
            try
            {
                return Assembly.GetAssembly(cl).CreateInstance(cl.FullName);
            }
            catch (Exception x)
            {
            }
            return null;
        }

        /// <summary>
        /// 初始化值
        /// </summary>
        /// <param name="h"></param>
        /// <param name="key"></param>
        /// <param name="initialValue"></param>
        /// <returns></returns>
        public static Object initHash(IDictionary<Object, Object> h, Object key, Object initialValue)
        {
            lock (h)
            {
                Object current = null;
                if (h.ContainsKey(key))
                {
                    current = h[key];
                    initialValue = current;
                }
                else
                {
                    if (current == null)
                    {
                        h[key] = initialValue;
                    }

                   
                }
            }
            return initialValue;
        }
        


        public static Object getListener(Object bag, int index)
        {
            if (index == 0)
            {
                if (bag == null)
                    return null;
                if (!(bag is Object[]))
                    return bag;
                Object[] array = (Object[])bag;
                // bag has at least 2 elements if it is array
                if (array.Length < 2) throw new ArgumentException();
                return array[0];
            }
            else if (index == 1)
            {
                if (!(bag is Object[]))
                {
                    if (bag == null) throw new ArgumentException();
                    return null;
                }
                Object[] array = (Object[])bag;
                // the array access will check for index on its own
                return array[1];
            }
            else
            {
                // bag has to array
                Object[] array = (Object[])bag;
                int L = array.Length;
                if (L < 2) throw new ArgumentException();
                if (index == L)
                    return null;
                return array[index];
            }
        }

        /**
     * If initCause methods exists in Throwable, call
     * <tt>ex.initCause(cause)</tt> or otherwise do nothing.
     * @return The <tt>ex</tt> argument.
     */
        public static Exception initCause(Exception ex,
                                                 Exception cause)
        {
            if (Throwable_initCause != null)
            {
                Object[] args = { cause };
                try
                {
                    Throwable_initCause.Invoke(ex, args);
                }
                catch (Exception e)
                {
                    // Ignore any exceptions
                }
            }
            return ex;
        }

        private static MethodInfo Throwable_initCause = null;
    }// end for class
}
